#include <Windows.h>
#include <string.h>
#include "GameUtil.h"
#include "StringUtil.h"
using namespace std;
static const int s_base = RAND_MAX;
string GetTimeString() {
	SYSTEMTIME sys;   
	GetLocalTime(&sys);
	return StringUtil::format("%4d/%02d/%02d %02d:%02d:%02d.%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds);	
}


std::string GetDateTimeString()
{
	SYSTEMTIME sys;
	GetLocalTime(&sys);
	return StringUtil::format("%4d/%02d/%02d %02d:%02d:%02d", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond);
}

std::string GetDateString()
{
	SYSTEMTIME sys;   
	GetLocalTime(&sys);
	return StringUtil::format("%4d-%02d-%02d",sys.wYear,sys.wMonth,sys.wDay);
}


std::string GetExecPath()
{
	char path[4096] = {};
	GetModuleFileNameA(NULL, path, sizeof(path));
	char* pos = strrchr(path, '/');
	
	if(!pos) {
		pos = strrchr(path, '\\');
	}

	if(pos) {
		*pos = '\0';
	}

	while(true) {
		pos = strrchr(path, '\\');

		if(pos) {
			*pos = '/';
		} else {
			break;
		}
	}
	return path;
}

std::string GetTimeStringWithoutSpace()
{
	SYSTEMTIME sys;   
	GetLocalTime(&sys);
	return StringUtil::format("%4d-%02d-%02d %02d_%02d_%02d.%03d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute, sys.wSecond,sys.wMilliseconds);	
}

std::string CancatPath( const string& path1, const string& fileName )
{
	char spliter = '/';
	int index = (int)path1.rfind('/');

	if(index < 0) {
		index =  (int)path1.rfind('\\');

		if(index >= 0) {
			spliter = '\\';
		}
	}

	if(index == path1.size() - 1) {
		return path1 + fileName;
	} else {
		return path1 + spliter + fileName;
	}
}


bool getResultOfPercent(double percent) {

	int pos = rand() % s_base;
	int range =  (int)(s_base * percent);
	return pos < range;
}

std::string GetExecPathFileName( const std::string& fileName )
{
	return CancatPath(GetExecPath(), fileName);
}

int doubleToInt( double input )
{
	return (int)(input + 0.5);
}

int getIntFromBuffer(unsigned char* input, int inputLen)
{
	int ret = 0;
	for (int i = 0; i < inputLen; i++) {
		ret += ret * 256 + input[i];
	}
	return ret;
}

void intToBuffer(int value, unsigned char * buffer)
{
	buffer[0] = (value >> 24) & 0xff;
	buffer[1] = (value >> 16) & 0xff;
	buffer[2] = (value >> 8) & 0xff;
	buffer[3] = value & 0xff;
}
